home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1562 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.1 KB  |  64 lines

  1. Path: lyra.csx.cam.ac.uk!93heb
  2. From: 93heb@eng.cam.ac.uk (H.E. Butterworth)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to access memory allocated  in function
  5. Date: 15 Jan 1996 14:14:18 GMT
  6. Organization: Cambridge University Engineering Department, UK
  7. Message-ID: <4ddnfq$ceh@lyra.csx.cam.ac.uk>
  8. References: <4ddbe3$so3@josie.abo.fi>
  9. NNTP-Posting-Host: tw800.eng.cam.ac.uk
  10.  
  11. In article <4ddbe3$so3@josie.abo.fi>, csundqvi@abo.fi (Christoffer Sundqvist) writes:
  12. > Hello
  13. > How can i access memory allocated dynamically in a function after i leave the 
  14. > function, something like this:
  15. > main()
  16. > {
  17. > int *p;
  18. > sub(p);
  19. > }
  20. > void sub(int *p)
  21. > {
  22. >  p = malloc(.....);
  23. > }
  24. > Thanks !
  25.  
  26.  
  27. How about:
  28.  
  29. void sub( int ** ppI )
  30. {
  31.     *ppI = malloc( sizeof( int ) );
  32.  
  33.     if( *ppI != NULL )
  34.     { 
  35.         **ppI = 42;
  36.     }
  37. }
  38.  
  39. main()
  40. {
  41.     int * pI;
  42.  
  43.     sub( &pI );
  44.  
  45.     if( pI != NULL )
  46.     {
  47.         printf( "%d\n", *pI );
  48.     }
  49.     else
  50.     {
  51.         printf( "malloc failed" );
  52.     }
  53. }
  54.  
  55. which should print the answer to the ultimate question of life the universe and
  56. everything - if given enough memory :-).
  57.  
  58. HB.
  59.